package top.xiesen.collection;

import java.util.LinkedList;

/**
 * 自定义Map集合的升级版 1. 提高查询的效率
 * 
 * @author Allen
 *
 */
public class MyMap002 {
	// 数组中放的是链表,链表中放的是(key,value)
	LinkedList[] arr = new LinkedList[999]; // map底层结构是: 数组 + 链表

	int size;

	public void put(Object key, Object value) {
		int a = key.hashCode() % arr.length;
		MyEntry e = new MyEntry(key, value);
		// 数组中数据不存在时,创建链表结构存储数据
		if (arr[a] == null) {
			LinkedList list = new LinkedList();
			arr[a] = list;
			list.add(e);
		} else {
			LinkedList list = arr[a];
			for (int i = 0; i < list.size(); i++) {
				MyEntry e2 = (MyEntry) list.get(i);
				if (e2.key.equals(key)) {
					e2.value = value; // 键值重复直接覆盖
					return;
				}
			}
			arr[a].add(e);
		}
	}

	public Object get(Object key) {
		// return arr[key.hashCode()%999];
		int a = key.hashCode() % arr.length;
		if (arr[a] != null) {
			LinkedList list = arr[a];
			for (int i = 0; i < list.size(); i++) {
				MyEntry e = (MyEntry) list.get(i);
				if (e.key.equals(key)) {
					return e.value;
				}
			}
		}
		return null;
	}

	public static void main(String[] args) {
		MyMap002 m = new MyMap002();
		m.put(1, 11111);
		m.put(1, 222222222);
		System.out.println(m.get(1));
	}

}
